<template>
	<div class="collect-variable-select">
		<el-form-item label="选择变量" :prop="prop" :required="true" ref="formItem">
			<el-select :value="getSelectedTextList()" :disabled="showDetail" placeholder="请选择要收集的变量" class="varscrollSelect" multiple no-data-text="暂无可收集变量" @remove-tag="onRemoveTag">
				<p class="collect-variable-customer-text">客户信息</p>
				<div class="collect-variable-role-box">
					<span class="role-text">角色：</span>
					<el-tag v-for="item in roleList" :key="item.id" class="role-tag" :class="{ activeTag: activeRoleId === item.id }" @click="checkRole(item.id)">{{ item.name }}</el-tag>
				</div>
				<el-checkbox :value="getFullCheckStatus()" @change="onCheckFull" style="margin: 10px 0 7px 18px">全选</el-checkbox>
				<span class="line"></span>
				<el-checkbox-group :value="selectedValues">
					<el-option v-for="item in getVariablesByRole()" :key="item.id">
						<el-checkbox :label="item.id" :checked="selectedValues.includes(item.id)" @change="checked => onCheck(checked, item)" style="width: 100%">{{ item.name }} </el-checkbox>
					</el-option>
				</el-checkbox-group>
			</el-select>
		</el-form-item>
	</div>
</template>

<script>
import { getAllRole, getVariablesAll } from '@/api/api.js';
export default {
	name: '',
	components: {},
	props: {
		nextStepOption: {
			type: Array,
			default: () => [],
			required: true
		},
		prop: {
			type: String,
			default: () => ''
		},
		value: {
			type: Array,
			required: true,
			default: () => []
		},
		showDetail: {
			type: Boolean,
			default: () => false
		}
	},
	data() {
		return {
			variableList: [], // 变量列表
			selectedValues: [], // 已选择的变量名
			checkStatus: {}, // 每个角色对应的全选状态
			roleList: [], // 角色列表
			activeRoleId: 0, // 当前选择的角色id
			scenId: JSON.parse(sessionStorage.getItem('sceneData'))?.id || this.$route.params.scenId,
			pageData: {
				page: 1,
				pageSize: 100000,
				total: 0
			}
		};
	},
	watch: {
		value: {
			handler: function(val) {
					this.selectedValues = [];
					this.$nextTick(() => {
						this.parseInValue();
					});
			},
			deep: true
		}
	},
	mounted() {
		this.initAllRole();
	},
	computed: {},
	methods: {
		// 初始化所有角色
		initAllRole() {
			getAllRole(this.scenId)
				.then(res => {
					// id: 302, name: '访客'
					this.roleList = res.data.data;
					this.activeRoleId = res.data.data[0].id;
					this.roleList.map(item => {
						this.checkStatus[item.id] = false;
					});
					this.getVariablesAll();
				})
				.catch(err => {
					console.log(err);
				});
		},
		getVariablesAll() {
			this.variableList = [];
			let param = {
				scenId: this.scenId,
				page: 1,
				pageSize: 10000
			};
			getVariablesAll(param)
				.then(res => {
					if (res.data.data && res.data.data.rows) {
						res.data.data.rows.map(item => {
							if (item.roleId) {
								const data = {
									id: item.id,
									name: item.name,
									roleId: item.roleId,
									dataMasking: item.dataMasking,
									params: item.params,
									url: item.url,
									method: item.method,
									linkedKey: item.linkedKey,
									isDefault: item.isDefault,
									key: item.name,
									property: item.type,
									content: '',
									initMode: item.initMode,
									scenId: this.scenId,
									roleName: item.bizscenario_role.name
								};
								this.variableList.push(data);
							}
						});
						this.pageData.total = res.data.data.count;
						this.parseInValue();
						this.$nextTick(() => {
							this.$refs.formItem.resetField();
						});
					} else {
						console.warn('get variable list error ', res.data);
					}
				})
				.catch(err => {
					console.log(err);
					this.$message.error('获取客户信息变量列表失败！');
				});
		},

		parseInValue() {
			this.selectedValues = [];
			if (this.value) {
				this.value.map(data => {
					for (const item of this.variableList) {
						if (data && data.id === item.id) {
							this.addSelectVariable(item.id);
							break;
						}
					}
				});

				this.checkFullSelectStatus();
			}
		},

		getVariablesByRole() {
			return this.variableList.filter(item => item.roleId === this.activeRoleId);
		},

		checkRole(id) {
			this.activeRoleId = id;
			this.checkFullSelectStatus();
		},
		onCheckFull(checked) {
			const list = this.getVariablesByRole();
			if (checked) {
				list.map(item => {
					this.addSelectVariable(item.id);
				});
				this.checkStatus[this.activeRoleId] = true;
			} else {
				list.map(item => {
					this.removeSelectVariable(item.id);
				});
				this.checkStatus[this.activeRoleId] = false;
			}
			this.onChange();
		},
		onRemoveTag(value) {
			for (const item of this.variableList) {
				const text = `客户信息-${item.roleName}-${item.name}`;
				if (value === text) {
					this.removeSelectVariable(item.id);
					break;
				}
			}
			this.checkFullSelectStatus();

			this.onChange();
		},

		onChange() {
			let list = [];
			this.selectedValues.map(id => {
				this.variableList.map(item => {
					if (id === item.id) {
						list.push(item);
					}
				});
			});
			this.$emit('input', this.prop, list);
		},

		onCheck(checked, item) {
			if (checked) {
				this.addSelectVariable(item.id);
			} else {
				this.removeSelectVariable(item.id);
			}
			this.checkFullSelectStatus();

			this.onChange();
		},
		addSelectVariable(vid) {
			if (!this.selectedValues.includes(vid)) {
				this.selectedValues.push(vid);
			}
		},
		removeSelectVariable(vid) {
			const index = this.selectedValues.indexOf(vid);
			if (index >= 0) {
				this.selectedValues.splice(index, 1);
			}
		},
		checkFullSelectStatus() {
			const list = this.getVariablesByRole();
			const listId = list.map(item => {
				return item.id;
			});

			const selected = this.selectedValues.filter(item => listId.includes(item));
			this.checkStatus[this.activeRoleId] = selected.length === listId.length;
		},
		getFullCheckStatus() {
			return this.checkStatus[this.activeRoleId] || false;
		},
		getSelectedTextList() {
			let list = [];
			this.selectedValues.map(id => {
				for (const item of this.variableList) {
					if (id === item.id) {
						list.push(`客户信息-${item.roleName}-${item.name}`);
						break;
					}
				}
			});

			return list;
		}
	}
};
</script>

<style lang="less">
.collect-variable-select {
}
.collect-variable-select .varSelect {
	margin-top: 10px;
	max-height: 90px;
	overflow-y: auto;
}
.collect-variable-select .varscrollSelect .el-select__tags {
	max-height: 90px;
	overflow-y: auto;
}
.line {
	height: 2px;
	background: #eee;
	// width: 96%;
	display: block;
	margin-left: 10px;
}
.collect-variable-customer-text {
	font-size: 13px;
	font-family: PingFang SC;
	font-weight: 500;
	color: #727378;
	margin-left: 16px;
	padding-top: 7px;
}
.collect-variable-role-box {
	margin: 18px 0 0 16px;
	.role-text {
		font-size: 13px;
		font-family: PingFang SC;
		font-weight: 400;
		color: #999999;
	}
	.role-tag {
		height: 32px;
		background: #ffffff;
		border-radius: 4px;
		color: #6784f2;
		margin: 0 7px;
		cursor: pointer;
	}
	.activeTag {
		height: 32px;
		border-radius: 4px;
		background-color: #e7f2fe;
		color: #5374f2;
		margin: 0 7px;
		cursor: pointer;
	}
}
</style>
